package com.tinysoft.gameframework;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

public class MainThread extends Thread {

	private SurfaceHolder surfaceHolder;
	private MainView mainView;
	private boolean running = false;

	public MainThread(SurfaceHolder _surfaceHolder, MainView _mainView) {
		surfaceHolder = _surfaceHolder;
		mainView = _mainView;
	}
	
	public SurfaceHolder getSurfaceHolder() {
		return surfaceHolder;
	}
	
	public void setRunning(boolean run) {
			running = run;
	}
	
	@Override
	public void run() {
		Log.i("MainThread", "run called:" + running);
		try {
			Canvas c;
			while (running) {
				c = null;
				try {
					c = surfaceHolder.lockCanvas(null);
					synchronized(surfaceHolder) {
						try {
							assert(mainView != null);
							assert(c != null);							
							mainView.onDraw(c);
							Thread.sleep(10);
						}
						catch (Exception e) {
							Log.e("MainThread", e.toString());
						}
					}
				}
				finally {
					if (c != null) 
						surfaceHolder.unlockCanvasAndPost(c);
				}
			}
		}
		catch (Exception e) {
			Log.e("MainThread", e.toString());
		}
	}
}
